package com.yswl.pri.picture;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yswl.pri.R;
import com.yswl.pri.eventbus.PictureDialogEvent;
import com.yswl.pri.picture.entry.BaiduImageBean;
import com.yswl.pri.picture.entry.ImageBean;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import yswl.com.klibrary.base.BaseRecyclerAdapter;
import yswl.com.klibrary.base.BaseViewHolder;
import yswl.com.klibrary.base.MFragment;
import yswl.com.klibrary.http.CallBack.HttpCallback;
import yswl.com.klibrary.http.HttpClientProxy;
import yswl.com.klibrary.http.okhttp.MScreenUtils;
import yswl.com.klibrary.util.L;
import yswl.com.klibrary.util.MUrlUtil;

/**
 * 来源:百度接口
 * 单一
 */
public class PictureListFragment extends MFragment implements HttpCallback<JSONObject> {
    private static final String TAG = PictureListFragment.class.getSimpleName();
    private static final int LOAD_MORE = 1;
    private static final int REFRESH = 2;
    int currPage = 0;
    int showCount = 10;
    String keyString = "美女";
    String keyString2 = "全部";

    ImagsListAdapter mAdapter;
    RefreshLayout refreshLayout;
    PictureDialog dialogFrg;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_pic_list, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        //initUI
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                loadData(REFRESH);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                loadData(LOAD_MORE);
            }
        });
        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        SpacesItemDecoration decoration = new SpacesItemDecoration(5);
        recyclerView.addItemDecoration(decoration);
        mAdapter = new ImagsListAdapter(getActivity(), null, R.layout.adapter_baidu_image_item);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (dialogFrg == null)
                    dialogFrg = PictureDialog.getInstance();
                dialogFrg.show(getChildFragmentManager(), "baiduimage");
                PictureDialogEvent.postEvent(defultImagBean, position);
            }
        });
//        DividerItemDecoration decoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
//        decoration.setDrawable(getResources().getDrawable(R.drawable.divider_item));
//        recyclerView.addItemDecoration(decoration);
        recyclerView.setAdapter(mAdapter);
        loadData(REFRESH);
    }

    List<ImageBean> defultImagBean = new ArrayList<>();

    List<ImageBean> copyImageData() {
        List<BaiduImageBean> baiduImageBeans = mAdapter.getList();
        if (baiduImageBeans == null || baiduImageBeans.size() == 0) return null;
        List<ImageBean> imageBeans = new ArrayList<>();
        for (int i = 0; i < baiduImageBeans.size(); i++) {
            BaiduImageBean currBai = baiduImageBeans.get(i);
            ImageBean currIma = new ImageBean();
            currIma.image_url = currBai.getDownload_url();
            currIma.image_height = currBai.getImage_height();
            currIma.image_width = currBai.getImage_width();
            imageBeans.add(currIma);
        }
        return imageBeans;
    }

    private void loadData(int Mode) {
        if (Mode == LOAD_MORE) currPage++;
        if (Mode == REFRESH) currPage = 0;
        String url = MUrlUtil.getUrl(this, R.string.url_baidu_image_search, currPage * showCount, showCount, keyString, keyString2);
        HttpClientProxy.getInstance().getAsyn(url, Mode, null, this);
    }

    @Override
    public void onSucceed(int requestId, JSONObject result) {
        L.d(TAG, " onSucceed : " + result);
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        int total = result.optInt("totalNum");
        if (total > 0) {
            if (requestId == REFRESH) {
                ArrayList<BaiduImageBean> images = BaiduImageBean.jsonToList(result);
                mAdapter.setList(images);
            } else {
                ArrayList<BaiduImageBean> images = BaiduImageBean.jsonToList(result);
                mAdapter.addList(images);
            }
            defultImagBean = copyImageData();
        }


    }

    @Override
    public void onFail(int requestId, String errorMsg) {
        L.e(TAG, " onFail : " + errorMsg);
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

    public class ImagsListAdapter extends BaseRecyclerAdapter<BaiduImageBean> {

        int widht;

        public ImagsListAdapter(Context mContext, List<BaiduImageBean> mList, int itemLayoutId) {
            super(mContext, mList, itemLayoutId);
            widht = MScreenUtils.getScreenWidth(mContext) / 2;
            L.d("TAG", " 屏幕width :" + widht);
        }

        @Override
        public void onBind(BaseViewHolder holder, BaiduImageBean baiduImageBean, int position) {
            ImageView imageView = holder.findById(R.id.image);
            ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();

            double currWidth = baiduImageBean.getImage_width();
            double currHeight = baiduImageBean.getImage_height();
            if (baiduImageBean.getImage_width() < widht) {
                currWidth = widht;
                currHeight = (widht / (double) baiduImageBean.getImage_width()) * baiduImageBean.getImage_height();
            }
            layoutParams.width = (new Double(currWidth)).intValue();
            layoutParams.height = (new Double(currHeight)).intValue();
            L.e("TAG", String.format(" width :%1$s, height :%2$s", baiduImageBean.getImage_width(), baiduImageBean.getImage_height()));
            L.e("TAG", String.format("new width :%1$s,new height :%2$s", currWidth, currHeight));

            Glide.with(mContext)
                    .applyDefaultRequestOptions(new RequestOptions().override(layoutParams.width, layoutParams.height)
                            .format(DecodeFormat.PREFER_RGB_565)).asBitmap()
                    .load(baiduImageBean.getImage_url()).thumbnail(0.01f).into(imageView);
        }
    }
}
